//监听快捷键
import { useKeyPress } from 'ahooks';
import { deleteComponent,copyOneComponent,pasteComponent,selectPreComponent,selectNextComponent } from '../store/ComponentReducer';
import { useDispatch } from 'react-redux';
import {ActionCreators} from 'redux-undo'

const isactiveElement = ()=>{
    const activeElement = document.activeElement
    if(activeElement === document.body || activeElement?.matches('div[role="button"]') ){
        return true
    }else{
        return false
    }
}

const useBindKeyPress = ()=>{
    
    const dispatch = useDispatch()
   
    useKeyPress(['delete','backspace'], () => {
        if(!isactiveElement()) return
        dispatch(deleteComponent())
    });

    useKeyPress('ctrl.c', () => {
        if(!isactiveElement()) return
        dispatch(copyOneComponent())
    });

    useKeyPress('ctrl.v', () => {
        if(!isactiveElement()) return
        dispatch(pasteComponent())
    });

    useKeyPress('uparrow', () => {
        if(!isactiveElement()) return
        dispatch(selectPreComponent())
    });

    useKeyPress('downarrow', () => {
        if(!isactiveElement()) return
        dispatch(selectNextComponent())
    });

    useKeyPress('ctrl.z', () => {
        if(!isactiveElement()) return
        dispatch(ActionCreators.undo())
    },{
        exactMatch:true
    });

    useKeyPress('ctrl.shift.z', () => {
        if(!isactiveElement()) return
        dispatch(ActionCreators.redo())
    });
}


export default useBindKeyPress